/**
 * Created by sa on 2016/9/22.
 */
var fs = require('fs');
var casper = require('casper').create({
  clientScripts: [
    'script/jquery-1.7.1.min.js'      // These two scripts will be injected in remote
  ],
  pageSettings: {
    loadImages: true,
    loadPlugins: false,
    userAgent: 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/537.36 LBBROWSER'
  },
  //logLevel: "debug",//日志等级
  logLevel: "error",//日志等级
  verbose: true,    // 记录日志到控制台
  timeout: 60000,//60秒超时，退出
});

var head = {
  method: 'get',
  headers: {
    "X-Forwarded-For": "120.25.224.51"
  },
  encoding: 'utf8'
}


casper.start();

var src = "";

casper.viewport(1024, 1024);

casper.thenOpen('http://www.httpuseragent.org/',
  head,
  function () {
    //读取广告承载页
    src = this.evaluate(function () {
      var aswift_1 = $('#aswift_1').contents().find("iframe");
      return aswift_1.attr("src");
    });
    if (src) {
      console.log("以获取到src")
      fs.write("AdGoogleTest_url.txt", src + "\n", 'a+');
    }
    //加载解析
    openAdUrl();
  })


function openAdUrl() {
  console.log("casperObj start")
  casper.open(src, head, function () {
  })
  //保存广告图片
  saveImg('ad');

  var hrefBB = null;

  //获取广告url
  casper.then(function () {
    console.log("openAdUrl start int")
    //this.echo(this.getHTML());
    hrefBB = this.evaluate(function () {
      //var href = $("#adContent-clickOverlay").attr("href")
      //获取广告url
      var href = $("a:eq(0)").attr("href")
      return href;
    });

    if (hrefBB) {
      if(hrefBB.indexOf('/') === 0){
        hrefBB = 'https://adclick.g.doubleclick.net' + hrefBB;
      }
      fs.write("AdGoogleTest.txt", hrefBB + "\n", 'a+');
      console.log("openAdUrl hrefBB ok")
    }

    //打开广告url
    casper.open(hrefBB, head, function () {
      this.echo(this.getCurrentUrl());
    })

  });
}

//保存追踪图片
casper.then(function () {
  var pathP = 'AdGoogle_tag_' + new Date().valueOf() + '.png'
  this.captureSelector(pathP, 'body');
  console.log("tag save img");
});

function saveImg(key){
  casper.then(function () {
    var pathP = 'AdGoogle_'+ key +'_' + new Date().valueOf() + '.png'
    this.captureSelector(pathP, 'body');
    console.log( key +" save img");
  });
}

casper.run(function () {
  //this.echo(this.getCurrentUrl());
});

